/**
 * 页面白屏监控
 */
import { ReportType } from './constant';
import { ReportParams } from './types';
import Utils from './utils';

export default class WhiteScreen {
	constructor(
		private callback: (params: ReportParams) => void,
		private filterElements?: Array<string>
	) {
		Utils.log('页面白屏监控初始化成功');
		this.init();
	}

	getSelector(element: HTMLElement): string {
		if (element.id) {
			return '#' + element.id;
		} else if (element.className) {
			return (
				'.' +
				element.className
					.split(' ')
					.filter(item => !!item)
					.join('.')
			);
		} else {
			return element.nodeName.toLowerCase();
		}
	}

	checkWhiteScreen() {
		const elements = this.filterElements || ['html', 'body'];
		const w = window.innerWidth;
		const h = window.innerHeight;
		let emptyPoints = 0;

		// 判断元素是否为白屏元素
		const isWrapper = (element: HTMLElement) => {
			const selector = this.getSelector(element);
			if (elements.includes(selector)) {
				// 如果检查到的元素在白屏元素列表中，则认为该点为空白点
				emptyPoints++;
			}
		};

		// 创建检测点数组
		const points = [];

		// 主要轴线上的点
		for (let i = 1; i <= 9; i++) {
			points.push({ x: (w * i) / 10, y: h / 2 }); // 水平线
			points.push({ x: w / 2, y: (h * i) / 10 }); // 垂直线
		}

		// 四个角落的点
		points.push({ x: w * 0.1, y: h * 0.1 });
		points.push({ x: w * 0.9, y: h * 0.1 });
		points.push({ x: w * 0.1, y: h * 0.9 });
		points.push({ x: w * 0.9, y: h * 0.9 });

		points.forEach(point => {
			const elementsAtPoint = document.elementsFromPoint(point.x, point.y);
			const topElement = elementsAtPoint[0];

			if (topElement) {
				isWrapper(topElement as HTMLElement);
			}
		});

		// 检测中心点
		const centerElements = document.elementsFromPoint(w / 2, h / 2);
		const centerElement = centerElements[0];
		const centerSelector = this.getSelector(centerElement as HTMLElement);

		isWrapper(centerElement as HTMLElement);
		// 判断是否为白屏（80%的点为空白）
		const isWhiteScreen = emptyPoints >= points.length * 0.8;
		if (isWhiteScreen) {
			Utils.log('debug', '检测到白屏！');
			this.callback({
				type: ReportType.BLANKSCREEN,
				message: '检测到白屏',
				emptyPoints,
				totalPoints: points.length,
				screen: `${window.screen.width}X${window.screen.height}`, // 屏幕
				viewPoint: `${w}X${h}`, // 浏览器
				centerElement: centerSelector,
			});
		}
	}
	init() {
		Utils.onload(() => {
			this.checkWhiteScreen();
		});
	}
}
